package storage

import (
	"context"
	"fmt"
	tcos "github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
)

type CosGreeter interface {
	COS(region string, bucket string) CosInterface
}

type CosInterface interface {
	ListObject(prefix string) (result *tcos.BucketGetResult, err error)
	UploadFile(localPath string, key string) error
	DownloadFile(key string, localPath string) (err error)
}

type cos struct {
	s       *Storage
	region  string
	baseUrl string
	client  *tcos.Client
}

func newCos(s *Storage, region string, bucket string) CosInterface {
	c := &cos{
		s:       s,
		region:  region,
		baseUrl: fmt.Sprintf("https://%s.cos.%s.myqcloud.com", "%s", region),
	}
	u, _ := url.Parse(fmt.Sprintf(c.baseUrl, bucket))
	b := &tcos.BaseURL{BucketURL: u}
	client := tcos.NewClient(b, &http.Client{
		Transport: &tcos.AuthorizationTransport{
			SecretID:  c.s.credential.SecretId,
			SecretKey: c.s.credential.SecretKey,
		},
	})
	c.client = client
	return c
}

func (c *cos) ListObject(prefix string) (result *tcos.BucketGetResult, err error) {
	opt := &tcos.BucketGetOptions{
		Prefix:  prefix,
		MaxKeys: 100,
	}
	result, _, err = c.client.Bucket.Get(context.Background(), opt)
	return
}

func (c *cos) UploadFile(localPath string, key string) error {
	opt := &tcos.ObjectPutOptions{
		ObjectPutHeaderOptions: &tcos.ObjectPutHeaderOptions{
			ContentType: "text/html",
		},
	}
	res, err := c.client.Object.PutFromFile(context.Background(), key, localPath, opt)
	if err != nil {
		return err
	}
	fmt.Printf("%+v", res.Response)
	return nil
}

func (c *cos) DownloadFile(key string, localPath string) (err error) {
	res, err := c.client.Object.GetToFile(context.Background(), key, localPath, nil)
	if err != nil {
		return
	}
	fmt.Printf("%+v", res.Response)
	return nil
}

func (c *cos) DeleteObject(key string) error {
	res, err := c.client.Object.Delete(context.Background(), key)
	if err != nil {
		return err
	}
	fmt.Printf("%+v", res.Response)
	return nil
}

// ModifyObjectACL 修改对象访问控制权限
func (c *cos) ModifyObjectACL(key string, acl string) error {
	opt := &tcos.ObjectPutACLOptions{
		Header: &tcos.ACLHeaderOptions{
			XCosACL: acl,
		},
	}
	res, err := c.client.Object.PutACL(context.Background(), key, opt)
	if err != nil {
		return err
	}
	fmt.Printf("%+v", res.Response)
	return nil
}

func (c *cos) GetObjectACL(key string) error {
	acl, _, err := c.client.Object.GetACL(context.Background(), key)
	if err != nil {
		return err
	}
	fmt.Printf("%+v", acl)
	return nil
}

func (c *cos) GetObjectVersionInfo(key string) {

}

func (c *cos) ModifyBucketPolicy() {

}

func (c *cos) GetBucketPolicy() {

}

func (c *cos) DeleteBucketPolicy() {

}
